package com.zhengsr.corelib.net;

import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.zhengsr.CoreManager;

import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.fastjson.FastJsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by zhengshaorui
 * Time on 2018/8/14
 */

public class HttpCreate {

    private final static HashMap<String,List<Cookie>> COOKIEDSTORE = new HashMap<>();
    /**
     * 获取retrofit服务
     * @return
     */
    public static HttpServiceApi getService(){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(CoreManager.getBaseUrl())
                //转字符串
                .addConverterFactory(ScalarsConverterFactory.create())
                //fastjson
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(OkHttpHolder.BUILDER)
                .build();
        return retrofit.create(HttpServiceApi.class);
    }

    /**
     * 配置okhttp3 client
     */
    static ClearableCookieJar cookieJar =
            new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(CoreManager.getContext()));
    private static class OkHttpHolder{
        static OkHttpClient BUILDER = new OkHttpClient.Builder()
                .connectTimeout(2, TimeUnit.SECONDS)
                //.addInterceptor(new AddCookiesInterceptor())
               // .addInterceptor(new SaveCookieIntecepter())
                .cookieJar(cookieJar)
                .build();
    }
}
